<?php
/**
*@author 雷雷
*/
namespace app\common\controller;


use app\admin\controller\Base;
use think\facade\App;
use think\facade\Db;
use think\Response;

class Code
{
    /**获取所有的表
     * @return mixed
     */
    public function getTable(){
        $tables = Db::query("show tables");
        return $tables;
    }

    /**获取所有字段
     * @param $tableName
     */
    public function getTableFail($tableName){
        $str = "show COLUMNS FROM ".$tableName;
        $data=Db::query($str);
        return $data;
    }
    /**获取所有字段注释
     * @param $tableName
     */
    public function getTableFailComment($tableName){
        $str = "SHOW FULL COLUMNS FROM ".$tableName;
        $data=Db::query($str);
        return $data;
    }

    /**
     * 生成控制器
     * @param $tableName
     * @return string
     */
    public function genController($tableName){
        $original=$tableName;
        $tableName=str_replace("_","",$tableName);
        $fail=$this->getTableFail($original);
        $template=$this->templateController($tableName,$fail,$original);
        $apitalize = ucwords($tableName);
        //判断当前控制器是否存在
        if (file_exists(App::getAppPath().'controller/'.$apitalize.'.php')){
            return "控制器已存在";
            //unlink(App::getAppPath().'controller\\'.$apitalize.'.php');
        }
        file_put_contents(App::getAppPath().'controller/'.$apitalize.'.php',$template,FILE_APPEND | LOCK_EX);

    }
    /**
     * 生成模型
     * @param $tableName
     * @return string
     */
    public function genModel($tableName){
        $original=$tableName;
        $tableName=str_replace("_","",$tableName);
        $fail=$this->getTableFail($original);
        $template=$this->templateModel($original,$fail,$original);

        $noprefix=explode('_', $original);
        $apitalize = ucwords($noprefix[1]);

        //判断当前控制器是否存在
        if (file_exists(App::getAppPath().'model/'.$apitalize.'.php')){
            return "模型已存在";
            //unlink(App::getAppPath().'controller\\'.$apitalize.'.php');
        }
        file_put_contents(App::getAppPath().'model/'.$apitalize.'.php',$template,FILE_APPEND | LOCK_EX);

    }

    /**
     * 生成视图
     * @param $tableName
     * @return string
     */
    public function genView($tableName){
        $original=$tableName;
        $tableName=str_replace("_","",$tableName);
        $Comment = $this->getTableFailComment($original);
        $template=$this->templateView($tableName,$Comment);
        if(!is_dir(App::getRootPath().'view/'.$tableName)){
            mkdir(iconv("UTF-8", "GBK", App::getAppPath().'view/'.$tableName),0777,true);
        }
        file_put_contents(App::getAppPath().'view/'.$tableName."/".'index.html',$template,FILE_APPEND | LOCK_EX);
    }
    /**
     * 生成视图
     * @param $tableName
     * @return string
     */
    public function genAdd($tableName){
        $original=$tableName;
        $tableName=str_replace("_","",$tableName);
        $Comment = $this->getTableFailComment($original);
        $template=$this->templateAdd($Comment);

        file_put_contents(App::getAppPath().'view/'.$tableName."/".'add.html',$template,FILE_APPEND | LOCK_EX);
    }
    /**
     * 生成视图
     * @param $tableName
     * @return string
     */
    public function genEdit($tableName){
        $original=$tableName;
        $tableName=str_replace("_","",$tableName);
        $Comment = $this->getTableFailComment($original);
        $template=$this->templateEdit($Comment);
        file_put_contents(App::getAppPath().'view/'.$tableName."/".'edit.html',$template,FILE_APPEND | LOCK_EX);
    }
    /**
     * 生成控制器
     * @param $tableName
     * @param $fail
     * @param $original
     * @return string
     */
    public function templateController($tableName,$fail,$original){
        $str = "";
        foreach ($fail as $key){
            $str .="'".$key['Field']."',";
        }
        $str = rtrim($str,',');
        $letter = $tableName;
        $apitalize = ucwords($tableName);
        $noprefix=explode('_', $original);
        $model = $noprefix[1].'Model';
        $usemodel = ucwords($noprefix[1]);
        return "<?php
        namespace app\admin\controller;
        use app\common\controller\Curd;
        use think\\facade\View;
        use app\admin\model\\$usemodel as $model;
        class $apitalize extends Base
        {
            
            public function index(){
            \$data =request()->param('searchParams');
            if (request()->param('limit') != null && request()->param('page') != null){
                \$search = json_decode(\$data, true);
                if(\$search==Null){
                    \$search = ['id'=>0];
                }
                \$Model = new $model();
                \$list =\$Model->withSearch(array_keys(\$search),\$search)->paginate([
                    'list_rows'=> request()->param('limit'),
                    'var_page' => 'page',
                    'query' =>request()->param()
                ]);

            \$count = $model::count();
            return \$this->success(\$list,'成功',\$count,0);
            }
            return View::fetch();
       }
              /**添加页
             * @return string
             */
            public function add(){
        
                return View::fetch();
            }
            /**
         * 编辑页
         * @return string
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\DbException
         * @throws \think\db\exception\ModelNotFoundException
         */
        public function edit(){
            \$id = request()->param('id');
            View::assign('data', $model::where('id',\$id)->find());
            return View::fetch();
        }
        /**添加管理员
         * @return \think\Response|\think\response\Redirect
         */
        public function addData()
        {
        \$data = request()->param();
        \$res =$model::insert(\$data);
        if(\$res){
            return \$this->success([],'成功~',0,200);
        }
       }
        /**
         * 编辑提交
         * @return \think\Response
         */
        public function editData(){
            //仅能POST访问
            if(!(request()->isPost())){
                //重定向
                return redirect((string)url('/index'));
            }
            \$data = request()->param();
            \$res = $model::update(\$data);
            if (\$res){
                return \$this->success([],'成功~',0,200);
            }else{
                return \$this->success([],'失败~',0,4000);
            }
        }    
            
            public function delete(){
               \$id = request()->param('id');
                \$res = $model::where('id',\$id)->delete();
                if (\$res){
                    return \$this->success([],'成功~',0,200);
                }else{
                    return \$this->success([],'失败~',0,400);
                }
            }
           
            
            public function batchDelete(){
               \$ids = request()->param('data');
                \$data = json_decode(\$ids);
                \$arr = \$this->object_array(\$data);
                foreach (\$arr as \$k =>\$v) {
                    
                    \$res = $model::delete(\$v['id']);
        
                }
                if (\$res){
                    return \$this->success([],'成功~',0,200);
                }else{
                    return \$this->success([],'失败~',0,4000);
                }    
                }
        }
        ";
    }
    /**
     * 生成模型
     * @param $tableName
     * @param $fail
     * @param $original
     * @return string
     */
    public function templateModel($tableName,$fail,$original){
        $noprefix=explode('_', $original);
        $apitalize = ucwords($noprefix[1]);
        $str = '';


        return "<?php
        namespace app\admin\model;
        use think\Collection;
        use think\Model;
        
        class $apitalize extends Model
        {
            // 开启自动写入时间戳字段
            protected \$autoWriteTimestamp = 'int';
            // 定义时间戳字段名
            protected \$createTime = 'createtime';
            protected \$updateTime = 'updatetime';
        
        
            public function searchIdAttr(\$query,\$value,\$data){
                \$query->where('id','>',\$value);
            }
           
           }";
    }
    public function templateView($tableName,$Comment){
        $str = '';$str1 = '';
        foreach ($Comment as $field){
            if (strpos($field['Field'], 'content') !== false){
                continue;
            }

            $str .= "<div class=\"layui-inline\">
                                    <label class=\"layui-form-label\">".$field['Comment']."</label>
                                    <div class=\"layui-input-inline\">
                                        <input type=\"text\"  name=".$field['Field']." autocomplete=\"off\" class=\"layui-input\">
                                    </div>
                                </div>
                                ";

        }
        foreach ($Comment as $field){
            $str1 .= "{field:"."'".$field['Field']."'".", width: 120,"."title:"."'".$field['Comment']."'"."},";
        }
        return
            "<!DOCTYPE html>
            <html>
            <head>
            <meta charset=\"utf-8\">
            <title>$tableName</title>
            <meta name=\"renderer\" content=\"webkit\">
            <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">
            <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">
            <link rel=\"stylesheet\" href=\"{__LIB__}/layui-v2.5.5/css/layui.css\" media=\"all\">
            <link rel=\"stylesheet\" href=\"{__CSS__}/public.css\" media=\"all\">
        </head>
        <body>
        <div class=\"layuimini-container\">
            <div class=\"layuimini-main\">
        
                <fieldset class=\"table-search-fieldset\">
                    <legend>搜索信息</legend>
                    <div style=\"margin: 10px 10px 10px 10px\">
                        <form class=\"layui-form layui-form-pane\" action=\"\">
                            <div class=\"layui-form-item\">
                               $str
                                <div class=\"layui-inline\">
                                    <button type=\"submit\" class=\"layui-btn layui-btn-primary\"  lay-submit lay-filter=\"data-search-btn\"><i class=\"layui-icon\"></i> 搜 索</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </fieldset>
        
                <script type=\"text/html\" id=\"toolbarDemo\">
                    <div class=\"layui-btn-container\">
                        {if \$add=='true'}<button class=\"layui-btn layui-btn-normal layui-btn-sm data-add-btn\" lay-event=\"add\"> 添加 </button>{/if}
                        {if \$delete=='true'}<button class=\"layui-btn layui-btn-sm layui-btn-danger data-delete-btn\" lay-event=\"delete\"> 删除 </button>{/if}
                    </div>
                </script>
        
                <table class=\"layui-hide\" id=\"currentTableId\" lay-filter=\"currentTableFilter\"></table>
        
                <script type=\"text/html\" id=\"currentTableBar\">
                    {if \$edit=='true'}<a class=\"layui-btn layui-btn-normal layui-btn-xs data-count-edit\" lay-event=\"edit\">编辑</a>{/if}
                    {if \$delete=='true'}<a class=\"layui-btn layui-btn-xs layui-btn-danger data-count-delete\" lay-event=\"delete\">删除</a>{/if}
                </script>
        
            </div>
        </div>
        <script src=\"{__LIB__}/layui-v2.5.5/layui.js\" charset=\"utf-8\"></script>
        <script>
            layui.use(['form', 'table'], function () {
                var $ = layui.jquery,
                    form = layui.form,
                    table = layui.table;
        
                table.render({
                    elem: '#currentTableId',
                    url: 'index',
                    parseData: function(res){ //res 即为原始返回的数据
                        // console.log(res);
                        return {
                            \"code\": res.code, //解析接口状态
                            \"msg\": res.msg, //解析提示文本
                            \"count\": res.data.total, //解析数据长度
                            \"data\": res.data.data //解析数据列表
                        };
                    },
                    toolbar: '#toolbarDemo',
                    defaultToolbar: ['filter', 'exports', 'print', {
                        title: '提示',
                        layEvent: 'LAYTABLE_TIPS',
                        icon: 'layui-icon-tips'
                    }],
                    cols: [[
                        {type: \"checkbox\", width: 50},
                        $str1
                        {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: \"center\"}
                    ]],
                    limits: [10, 15, 20, 25, 50, 100],
                    limit: 15,
                    page: true,
                    skin: 'line'
                });
        
                // 监听搜索操作
                form.on('submit(data-search-btn)', function (data) {
                    // JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
                    var result = JSON.stringify(data.field);
                    table.reload('currentTableId', {
                        page: {
                            curr: 1
                        }
                        , where: {
                            searchParams: result
                        }
                    }, 'data');
                    return false;
                });
        
                /**
                 * toolbar监听事件
                 */
                table.on('toolbar(currentTableFilter)', function (obj) {
                    if (obj.event === 'add') {  // 监听添加操作
                        var index = layer.open({
                            title: '添加管理员',
                            type: 2,
                            shade: 0.2,
                            maxmin:true,
                            shadeClose: true,
                            area: ['40%', '90%'],
                            content: 'add.html',
                            end: function(layero, index){
                                table.reload('currentTableId', {}, 'data');
                            }
                        });
                        $(window).on(\"resize\", function () {
                            layer.full(index);
                        });
                    } else if (obj.event === 'delete') {  // 监听删除操作
                        var checkStatus = table.checkStatus('currentTableId')
                            , data = checkStatus.data;
                        console.log(JSON.stringify(data));
                        layer.confirm('真的要删除吗？', function (index) {
                            $.ajax({
                                url: \"batchDelete\", //后台数据请求地址
                                type:'post',
                                dataType:'json',
                                data:{'data':JSON.stringify(data)},
                                success:function (result) {
                                    layer.msg(result.msg, {
                                        icon: 1,
                                        time: 1000
                                    }, function(){
                                        table.reload('currentTableId', {}, 'data');
                                    });
                                },
                                error:function(result) {
                                    layer.msg(result.msg,{icon:2,time:1000});
                                },
                            });
                            layer.close(index);
                        });
                    }
                });
        
                //监听表格复选框选择
                table.on('checkbox(currentTableFilter)', function (obj) {
                    console.log(obj);
                });
        
                table.on('tool(currentTableFilter)', function(obj){
                    var data = obj.data;
                    if(obj.event === 'edit'){
                        layer.open({
                            type: 2
                            ,title: '编辑角色'
                            ,content: 'edit.html?id='+ data.id
                            ,maxmin: true
                            ,shadeClose : true
                            ,area: ['40%', '90%']
                            //编辑数据回显
                            ,end: function (layero, index) {
                                table.reload('currentTableId', {}, 'data');
                            }
                        });
                        $(window).on(\"resize\", function () {
                            layer.full(index);
                        });
                    } else if (obj.event === 'delete') {
                        layer.confirm('真的要删除吗？', function (index) {
                            $.ajax({
                                url: \"delete\", //后台数据请求地址
                                type:'post',
                                dataType:'json',
                                data:{'id':data.id},
                                success:function (result) {
                                    layer.msg(result.msg, {
                                        icon: 1,
                                        time: 1000
                                    }, function(){
                                        table.reload('currentTableId', {}, 'data');
                                    });
                                },
                                error:function(result) {
                                    layer.msg(result.msg,{icon:2,time:1000});
                                },
                            });
                            layer.close(index);
                        });
                    }
                });
        
            });
        </script>
        
        </body>
        </html>
            ";
    }

    /**
     * 添加页面
     * @param $Comment
     * @return string
     */
    public function templateAdd($Comment){
        $str = '';$str1 = ''; $str2 = '';
        unset($Comment[0]);
        foreach ($Comment as $field){
            if (strpos($field['Field'], 'content') !== false){
                continue;
            }
            if (strpos($field['Field'],'time') !==false){
                $str .="<div class=\"layui-inline\">
                    <label class=\"layui-form-label\">".$field['Comment']."</label>
                    <div class=\"layui-input-inline\">
                        <input type=\"text\" name=".$field['Field']." id=".$field['Field']." lay-verify=\"date\" placeholder=\"yyyy-MM-dd\" autocomplete=\"off\" class=\"layui-input\">
                    </div>
                </div>";
            }elseif (strpos($field['Field'],'status') !==false){
                $str2 .="if(data.field.".$field['Field']." == \"on\") {
                data.field.".$field['Field']." = \"1\";
            } else {
                data.field.".$field['Field']." = \"0\";
            }";
                $str .="<div class=\"layui-form-item\">
                    <label class=\"layui-form-label\">".$field['Comment']."</label>
                    <div class=\"layui-input-block\">
                        <input type=\"checkbox\" checked=\"\" name=".$field['Field']." lay-skin=\"switch\" lay-filter=\"switchTest\" lay-text=\"开启|关闭\">
                    </div>
                </div>";
            }else{
                $str .= "<div class=\"layui-form-item\">
                        <label class=\"layui-form-label\">".$field['Comment']."</label>
                        <div class=\"layui-input-block\">
                           <input type=\"email\"  name=".$field['Field']." placeholder=\"请输入...\" value=\"\" class=\"layui-input\">
                        </div>
                    </div>
                                ";
            }
            if (strpos($field['Field'],'time') !==false){
                $str1 .="
                laydate.render({
                        elem: '#".$field['Field']."'
                    });
                    ";
            }



        }

        return
            "<!DOCTYPE html>
        <html>
        <head>
            <meta charset=\"utf-8\">
            <title>layui</title>
            <meta name=\"renderer\" content=\"webkit\">
            <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">
            <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">
            <link rel=\"stylesheet\" href=\"{__LIB__}/layui-v2.5.5/css/layui.css\" media=\"all\">
            <link rel=\"stylesheet\" href=\"{__CSS__}/public.css\" media=\"all\">
            <style>
                body {
                    background-color: #ffffff;
                }
            </style>
        </head>
        <body>
        <div class=\"layui-form layuimini-form\">
                $str
            <div class=\"layui-form-item\">
                <div class=\"layui-input-block\">
                    <button class=\"layui-btn layui-btn-normal\" lay-submit lay-filter=\"saveBtn\">确认添加</button>
                </div>
            </div>
        </div>
        <script src=\"{__LIB__}/layui-v2.5.5/layui.js\" charset=\"utf-8\"></script>
        <script>
            layui.use(['form','laydate'], function () {
                var form = layui.form,
                    layer = layui.layer,
                    $ = layui.$,
                    laydate = layui.laydate;

                    $str1
        
                //监听提交
                form.on('submit(saveBtn)', function (data) {
                    $str2
                    $.ajax({
                        url: \"addData\", //后台数据请求地址
                        type:'post',
                        dataType:'json',
                        data:data.field,
                        success:function (result) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 1000
                            }, function(){
                                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                parent.layer.close(index); //再执行关闭
                            });
                        },
                        error:function(result) {
                            layer.msg(result.msg,{icon:2,time:1000});
                        },
                    });
                });
            });
        </script>
        </body>
        </html>";
    }
    public function templateEdit($Comment){
        $str = '';$str1 = '';$str2 = '';
        unset($Comment[0]);
        foreach ($Comment as $field){
            if (strpos($field['Field'], 'content') !== false){
                continue;
            }

            if (strpos($field['Field'],'time') !==false){
                $str .="<div class=\"layui-inline\">
                    <label class=\"layui-form-label\">".$field['Comment']."</label>
                    <div class=\"layui-input-inline\">
                        <input type=\"text\" name=".$field['Field']." id=".$field['Field']." lay-verify=\"date\" placeholder=\"yyyy-MM-dd\" autocomplete=\"off\" class=\"layui-input\">
                    </div>
                </div>";
            }elseif (strpos($field['Field'],'status') !==false){
                $str2 .="if(data.field.".$field['Field']." == \"on\") {
                data.field.".$field['Field']." = \"1\";
            } else {
                data.field.".$field['Field']." = \"0\";
            }";
                $str .="<div class=\"layui-form-item\">
                    <label class=\"layui-form-label\">".$field['Comment']."</label>
                    <div class=\"layui-input-block\">
                        <input type=\"checkbox\" checked=\"\" name=".$field['Field']." lay-skin=\"switch\" lay-filter=\"switchTest\" lay-text=\"开启|关闭\">
                    </div>
                </div>";
            }else{
                $str .= "<div class=\"layui-form-item\">
                        <label class=\"layui-form-label\">".$field['Comment']."</label>
                        <div class=\"layui-input-block\">
                           <input type=\"email\"  name=".$field['Field']." placeholder=\"请输入...\" value=\"\" class=\"layui-input\">
                        </div>
                    </div>
                                ";
            }
            if (strpos($field['Field'],'time') !==false){
                $str1 .="
                laydate.render({
                        elem: '#".$field['Field']."'
                    });
                    ";
            }

        }
        return
        "<!DOCTYPE html>
        <html>
        <head>
            <meta charset=\"utf-8\">
            <title>layui</title>
            <meta name=\"renderer\" content=\"webkit\">
            <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">
            <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">
            <link rel=\"stylesheet\" href=\"{__LIB__}/layui-v2.5.5/css/layui.css\" media=\"all\">
            <link rel=\"stylesheet\" href=\"{__CSS__}/public.css\" media=\"all\">
            <style>
                body {
                    background-color: #ffffff;
                }
            </style>
        </head>
        <body>
        <div class=\"layui-form layuimini-form\">
                $str
            <div class=\"layui-form-item\">
                <div class=\"layui-input-block\">
                    <input type=\"hidden\" name=\"id\" value=\"{\$data.id}\">
                    <button class=\"layui-btn layui-btn-normal\" lay-submit lay-filter=\"saveBtn\">确认修改</button>
                </div>
            </div>
        </div>
        <script src=\"{__LIB__}/layui-v2.5.5/layui.js\" charset=\"utf-8\"></script>
        <script>
            layui.use(['form','laydate'], function () {
                var form = layui.form,
                    layer = layui.layer,
                    $ = layui.$,
                    laydate = layui.laydate;
                    $str1
        
                //监听提交
                form.on('submit(saveBtn)', function (data) {
                    $str2
                    $.ajax({
                        url: \"editData\", //后台数据请求地址
                        type:'post',
                        dataType:'json',
                        data:data.field,
                        success:function (result) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 1000
                            }, function(){
                                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                                parent.layer.close(index); //再执行关闭
                            });
                        },
                        error:function(result) {
                            layer.msg(result.msg,{icon:2,time:1000});
                        },
                    });
                });
            });
        </script>
        </body>
        </html>";
    }
}